﻿using Blm.Utils.Extensions;
using Blm.Utils.Utility;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Ms;

namespace VisionCloud.Service.Ms
{
    /// <summary>
    /// 自动标注服务
    /// </summary>
    public class AutomaticService
    {
        private readonly string autoMaticServiceApi;
        private readonly ILogger<AutomaticService> logger;

        public AutomaticService(IConfiguration cfg, ILogger<AutomaticService> logger)
        {
            autoMaticServiceApi = cfg["AutoMaticServiceAPI"];
            this.logger = logger;
        }

        /// <summary>
        /// 调用自动标注服务生成热力图底图以及站点位置信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<AutoMaticResponseDto> CreateHouseMapImage(AutoMaticRequestDto dto)
        {
            using (var response = await HttpUtility.PostAsync(autoMaticServiceApi, dto.ToJsonStr(), 180))
            {
                if (response == null || !response.IsSuccessStatusCode || response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    logger.LogInformation($"自动标注接口： {autoMaticServiceApi} {dto.ToJsonStr()}");
                    logger.LogInformation($"自动标注接口： {autoMaticServiceApi}");
                    logger.LogInformation($"请求自动标注算法结果：resposeStatus = {response?.StatusCode}");
                    throw new OperationException("请求自动标注算法失败");
                }
                var responseStr = await response.Content.ReadAsStringAsync();
                var apiResult = responseStr.ToObject<ApiResultBase<AutoMaticResponseDto>>();
                if (apiResult == null || apiResult.Code != 0 || apiResult.Result == null)
                {
                    logger.LogInformation($"请求自动标注算法结果：statusCode = {response.StatusCode}，result = {responseStr}");
                    throw new OperationException("请求自动标注算法失败");
                }
                return apiResult.Result;
            }
        }
    }
}
